from selenium import webdriver
import os
import xlrd
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.keys import Keys
import pyperclip


class WalletUtil:
    # example
    # EXTENSION_PATH = 'E:\\autoOp\\ext\\metamask.crx'
    # word = 'lemon attack general push agent loud color civil evil solution okay inmate'
    # EXTENSION_ID = 'nkbihfbeogaeaoehlefnkodbefgpgknn'
    EXTENSION_PATH = None
    word = None
    EXTENSION_ID = None
    executablePath = None
    password = None

    def __init__(self, EXTENSION_PATH, word, EXTENSION_ID, executablePath, password) -> None:
        self.EXTENSION_PATH = EXTENSION_PATH
        self.word = word
        self.EXTENSION_ID = EXTENSION_ID
        self.executablePath = executablePath
        self.password = password

    def importSingleWallet(self):

        opt = webdriver.ChromeOptions()
        opt.add_extension(self.EXTENSION_PATH)
        # 加载用户目录数据
        opt.add_argument("--user-data-dir=" + os.getcwd() +
                         "/cache/" + self.word)
        # executablePath = "C:\Program Files\Google\Chrome\Application\chromedriver.exe"
        # 判断用户目录是否存在，否则创建目录和用户数据
        userDataDir = os.getcwd() + "/cache/" + self.word
        driverExt = None
        if (os.path.exists(userDataDir) == False or os.listdir(userDataDir) == []):
            os.makedirs(userDataDir)
            driverExt = webdriver.Chrome(
                chrome_options=opt, executable_path=self.executablePath)
            # driver = webdriver.Chrome()

            driverExt.get(
                'chrome-extension://{}/home.html#onboarding/welcome'.format(self.EXTENSION_ID))
            driverExt.implicitly_wait(10)
            windows = driverExt.window_handles
            driverExt.switch_to.window(windows[0])
            print(driverExt.title)

            try:
                return self.importwallet(driverExt, self.password)
            except:
                print('metamask无响应,刷新')
                driverExt.refresh()
                return self.importwallet(driverExt, self.password)
        else:
            driverExt = webdriver.Chrome(
                chrome_options=opt, executable_path=self.executablePath)
            return driverExt, 1

    def importwallet(self, driverExt, password):
        # 导入钱包
        # 如果没有get浏览器插件页面 无法定位到某个网页也就无法操作
        if (driverExt.title == 'MetaMask'):

            driverExt.find_element(
                By.XPATH, '//*[@id="onboarding__terms-checkbox"]').click()
            # 按钮：导入现有钱包
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/ul/li[2]/button').click()
            time.sleep(1)
            # 按钮：同意用户使用手册
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div/button[1]').click()

            # for i in range(0, 11):
            #     wordPath = '//*[@id="import-srp__srp-word-{n}"]'
            #     word = ['lemon', 'attack', 'general', 'push', 'agent', 'loud',
            #             'color', ' civil', 'evil', 'solution', 'okay', 'inmate']
            # driverExt.find_element(By.XPATH, wordPath.format(n=i)).send_keys(
            #     word[0])
            # os.system('pause')
            # # 添加字符到剪切板
            # pyperclip.copy(word)
            # # 黏贴钱包助记词
            # driverExt.find_element(
            #     By.XPATH, '//*[@id="import-srp__srp-word-1"]').send_keys(Keys.CONTROL, 'v')
            # # 按钮：确认添加钱包
            # driverExt.find_element(
            #     By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[4]/div/button').click()
            # 输入密码
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[2]/form/div[1]/label/input').send_keys(password)
            time.sleep(1)
            # 确认密码
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[2]/form/div[2]/label/input').send_keys(password)

            # 按钮:同意勾选框
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[2]/form/div[3]/label/input').click()
            # 按钮：导入钱包
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[2]/form/button').click()

            # os.system('pause')
            time.sleep(1)
            # 跳过账户安全
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[5]/button[1]').click()

            driverExt.find_element(
                By.XPATH, '//*[@id="popover-content"]/div/div/section/div[1]/div/div/label/input').click()

            driverExt.find_element(
                By.XPATH, '//*[@id="popover-content"]/div/div/section/div[2]/div/button[2]').click()

            # 按钮：完成
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[2]/button').click()
            # 按钮：下一步
            time.sleep(1)
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[2]/button').click()
            # 按钮：完成
            time.sleep(1)
            driverExt.find_element(
                By.XPATH, '//*[@id="app-content"]/div/div[2]/div/div/div/div[2]/button').click()

            # 关闭当前操作的窗口
            # driverExt.close()
            return driverExt, 0

        else:
            print('wrong page')

        # # 获取表格中sheet1的内容
        # excel = xlrd.open_workbook("E:/autoOp/eth.xls").sheet_by_index(0)
        # # 获取第一行的列名称
        # rows: list = excel.row_values(0)
        # # 获取Address列的所有内容
        # addressList = excel.col_values(rows.index('Seed Phrase'))
        # print(addressList[1])
        # 自动网页操作
        # for i in range(1, len(addressList)):
        #     print(addressList[i])

        # os.system('pause')
        # driver.execute_script('window.open('')')
        # driver.switch_to.window(driver.window_handles[1])
        # driver.get('chrome-extension://{}/popup.html'.format(EXTENSION_ID))
